package tic_tac_toe_game;

/**
 * author :  apurv verma
 * email  :  dapurv5@gmail.com
 */

public class GameState implements Cloneable{
	
	public final static int HUMAN=1;
	public final static int MACHINE=-1;
	public final static int VACANT=0;
	
	private int winner=0;
	public int count=0;
	public int board[][];

	
	public GameState(){
		board=new int[3][3];
	}
	
	/*
	 * TEST CONSTRUCTOR
	 */
	public GameState(int b[][]){
		board=new int[3][3];
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
				board[i][j]=b[i][j];
				if(b[i][j]==VACANT)
					count++;
			}
		}
		count=9-count;
	}
	
	public boolean hasBeenWon(){
		boolean result=false;
		if(board[0][0]==board[0][1] && board[0][0]==board[0][2]){
			result=true;
			winner=board[0][0];
		}
		else if(board[1][0]==board[1][1] && board[1][0]==board[1][2]){
			result=true;
			winner=board[1][0];
		}
		else if(board[2][0]==board[2][1] && board[2][0]==board[2][2]){
			result=true;
			winner=board[2][0];
		}
		else if(board[0][0]==board[1][0] && board[0][0]==board[2][0]){
			result=true;
			winner=board[0][0];
		}
		else if(board[0][1]==board[1][1] && board[0][1]==board[2][1]){
			result=true;
			winner=board[0][1];
		}
		else if(board[0][2]==board[1][2] && board[0][2]==board[2][2]){
			result=true;
			winner=board[0][2];
		}
		else if(board[0][0]==board[1][1] && board[0][0]==board[2][2]){
			result=true;
			winner=board[0][0];
		}
		else if(board[0][2]==board[1][1] && board[0][2]==board[2][0]){
			result=true;
			winner=board[0][2];
		}
		if(winner==0)
			result=false;
		return result;
	}

	public boolean humanHasWon(){
		if(winner==HUMAN)
			return true;
		return false;
	}

	public boolean machineHasWon(){
		if(winner==MACHINE)
			return true;
		return false;
	}

	public boolean isDraw(){
		if(count==9)
			return true;
		return false;
	}

	public void printBoard(){
		char symbols[]={'O',' ','X'};
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
				System.out.print(symbols[board[i][j]+1]+" ");
			}
			System.out.println();
		}
	}
	
	protected Object clone()throws CloneNotSupportedException{
		GameState g=new GameState();
		g.count=this.count;
		g.winner=this.winner;
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
				g.board[i][j]=this.board[i][j];
			}
		}
		return g;
	}
	
	public static int otherPlayer(int player){
		if(player==GameState.MACHINE)
			return GameState.HUMAN;
		else
			return GameState.MACHINE;
	}


}
